<template>
  <div class="tag">
    <template v-for="(tag, index) in state.tags" :key="tag">
      <a-tag :closable="index !== 0" @close="handleClose(tag)" @click="checked(state.tags[index])" :class="{active:state.tags[index].isChecked}">
        {{ tag.title }}
      </a-tag>
    </template>

  </div>
</template>
<script setup>
import {onMounted, reactive, watch} from 'vue';
const state = reactive({
  // 根据路由来判断
  tags: [{title:'首页',path:'/', isChecked:false}],
});



import {useRoute } from 'vue-router'
import router from "@/router/index.js";
const route = useRoute()

// 删除标签
const handleClose = removedTag => {
  console.log("输出的title",removedTag)
  const tags = state.tags.filter(tag => tag.title !== removedTag.title);
  state.tags = tags;
 console.log("11",tags)
  const tagsData = Object.keys(sessionStorage)
      .filter(key => key.startsWith('tags:'))
      .map(key => ({ key, value: sessionStorage.getItem(key) }));

  sessionStorage.removeItem("tags:"+removedTag.title);
  // 缓存没有数据就标识这个为首页并且路由到首页
  // todo 跳转首页
  if (tagsData===undefined){
    state.tags=[{title:'首页',path:'/', isChecked:true}]
  }

};
// 选中变颜色
const checked=tag=>{
  router.push(tag.path)
  // 点击路由跳转到对应页面
  // tag改变颜色（被点击的）
  // router.push(route.path)
  for (const zts of state.tags) {
    zts.isChecked=false
    if (tag.title===zts.title){
      zts.isChecked=true
    }
  }
  console.log("路径为"+tag.path)

}


watch(() => route.path, () =>{
  if (route.meta.title!=="首页"){
    const newsItem={title:'',path:'', isChecked:false}
    newsItem.title=route.meta.title;
    newsItem.path=route.path;
    newsItem.isChecked=true
    addTag(newsItem)
  }else {
    console.log("首页被选中",state.tags)
    state.tags.forEach(item=>{
      if (item.title==="首页"){
        console.log("进入首页")
        // 把缓存中的数据选中状态全部改为false
        Object.keys(sessionStorage)
            .filter(key => key.startsWith('tags:'))
            .forEach(key => {
              let value = sessionStorage.getItem(key);
              if (value) {
                let data = JSON.parse(value);
                data.isChecked = false;
                sessionStorage.setItem(key, JSON.stringify(data));
              }
            });
        // state.tags.forEach(item=>{item.isChecked=false})
        // console.log("监听",state.tags)
        state.tags.forEach(item=>{
          if (item.title==="首页"&&route.path==="/"||route.path===""){
            state.tags.forEach(item=>{item.isChecked=false})
            console.log("初始化",state.tags)
            item.isChecked=true
            // 缓存数据修改
            for (let key in sessionStorage) {
              if (sessionStorage.hasOwnProperty(key) && key.startsWith('tags:')) {
                let value = sessionStorage.getItem(key);
                if (value) {
                  let data = JSON.parse(value);
                  data.isChecked = false;
                  sessionStorage.setItem(key, JSON.stringify(data));
                }
              }
            }

          }
        })
      }
      if (item.title!=="首页"){
        item.isChecked=false
        // sessionStorage.setItem("tags:"+item.title,JSON.stringify(item))
      }
    })
  }
  const tagsData = Object.keys(sessionStorage)
      .filter(key => key.startsWith('tags:'))
      .map(key => ({ key, value: sessionStorage.getItem(key) }));
  if (tagsData===undefined){
    state.tags=[{title:'首页',path:'/', isChecked:true}]
  }


})
onMounted(()=>{
  const tagsData = Object.keys(sessionStorage)
      .filter(key => key.startsWith('tags:'))
      .map(key => ({ key, value: sessionStorage.getItem(key) }));
// 利用Set来辅助去重，这里将对象转换为字符串形式来判断唯一性
  tagsData.forEach(obj => {
    state.tags.push(JSON.parse(obj.value));
  });
  state.tags.forEach(item=>{
    if (item.title==="首页"&&route.path==="/"||route.path===""){
      state.tags.forEach(item=>{item.isChecked=false})
      console.log("初始化",state.tags)
      item.isChecked=true
      // 缓存数据修改
      for (let key in sessionStorage) {
        if (sessionStorage.hasOwnProperty(key) && key.startsWith('tags:')) {
          let value = sessionStorage.getItem(key);
          if (value) {
            let data = JSON.parse(value);
            data.isChecked = false;
            sessionStorage.setItem(key, JSON.stringify(data));
          }
        }
      }

    }
  })
  console.log("all:",state.tags)
})
function addTag(tag) {
  const existingTag = state.tags.find(item => item.title === tag.title);
  if (!existingTag) {
    console.log("进入add方法")
    state.tags.push(tag)
    state.tags.forEach(item=>{
      if (item.title===tag.title){
        item.isChecked=true
        if (item.title!=="首页"){
          sessionStorage.setItem("tags:"+item.title,JSON.stringify(item))
        }
      }else {
        item.isChecked=false
        if (item.title!=="首页"){
          sessionStorage.setItem("tags:"+item.title,JSON.stringify(item))
        }
      }
    })
  } else {
    // 把状态改为选中
    console.log('已有相同标题的标签，不能添加。');
    state.tags.forEach(item=>{
      if (item.title===tag.title){
        item.isChecked=true
        if (item.title!=="首页"){
          sessionStorage.setItem("tags:"+item.title,JSON.stringify(item))
        }
      }else {
        item.isChecked=false
        if (item.title!=="首页"){
          sessionStorage.setItem("tags:"+item.title,JSON.stringify(item))
        }
      }
    })
  }
}


</script>
<style scoped>
.tag{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 5px;
  margin-left: 12px;
  padding-top: 5px;
}
.active{
  width: auto;
  height: 24px;
  background-color: rgb(64, 158, 255);
  border-color: rgb(64, 158, 255);
}
</style>
